package com.olinsports.system.olinsportssystem.service;

import com.olinsports.system.olinsportssystem.model.*;
import com.olinsports.system.olinsportssystem.repository.SiteConsumptionDetailsRepository;
import com.olinsports.system.olinsportssystem.repository.SiteReservationRepository;
import com.olinsports.system.olinsportssystem.repository.SiteTimeRepository;
import com.olinsports.system.olinsportssystem.repository.SiteTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Administrator on 2017/7/22.
 */
@Service
public class SiteReservationService {
    @Autowired
    private SiteReservationRepository siteReservationRepository;
    @Autowired
    private SiteTimeRepository siteTimeRepository;
    @Autowired
    private SiteConsumptionDetailsRepository siteConsumptionDetailsRepository;
    @Autowired
    private SiteTypeRepository siteTypeRepository;
    @Autowired
    private HttpServletRequest request;


    public List<SiteReservation> selectAll(){
        return siteReservationRepository.selectAll();
    }


    public List<SiteReservation> selectByScheduledDate(String scheduledDate){
        List<SiteReservation> siteReservations = siteReservationRepository.selectByScheduledDate(scheduledDate);
        if(siteReservations.isEmpty()){
            return siteReservationRepository.selectByDateNull();
        } else {
            return siteReservationRepository.selectByScheduledDate(scheduledDate);
        }
    }

    @Transactional
    public int insertAll(SiteReservation siteReservation,String[] revTime,int plyKey){
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        SiteType siteType = siteTypeRepository.selectByPlaceKey(plyKey);
       // Calendar now = Calendar.getInstance();
        //String day = now.get(Calendar.YEAR)+"-"+(now.get(Calendar.MONTH) + 1)+"-"+now.get(Calendar.DAY_OF_MONTH);
        System.out.println(siteReservation.getScheduledDate());

        int s = 0;
        for(int i = 0;i<revTime.length;i++){
            SiteTime siteTime = siteTimeRepository.selectByTimeDate(revTime[i]);
            SiteReservation siteRev = siteReservationRepository.selectCheck(String.valueOf(siteReservation.getScheduledDate()),plyKey,siteTime.getTimeKey());

            if(siteRev == null){//没有重复
                if(siteReservation.getPrice() == 0){
                    siteReservation.setState("4");
                    siteReservation.setPayMethod("");
                } else {
                    siteReservation.setState("1");
                }
                siteReservation.setTimeKey(siteTime);
                //siteReservation.setScheduledDate(date);
                siteReservation.setRevKey(1);
                siteReservation.setPlaceKey(siteType);
                siteReservation.setSiteOrder(String.valueOf(date.getTime()));
                s = siteReservationRepository.insertAll(siteReservation);
                System.out.println("s = "+s);
            } else {
                s = 0;
                System.out.println("s b = "+s);
                break;
            }
        }
        System.out.println("s W = "+s);
        if(s > 0 && !siteReservation.getState().equals("4")){
            SiteConsumptionDetails siteConsumptionDetails = new SiteConsumptionDetails();
            siteConsumptionDetails.setSiteOrder(siteReservation.getSiteOrder());
            siteConsumptionDetails.setDate(date);
            siteConsumptionDetails.setVipNum(siteReservation.getVipNum());
            siteConsumptionDetails.setVipName(siteReservation.getVipName());
            siteConsumptionDetails.setVipTel(siteReservation.getPhone());
            siteConsumptionDetails.setPlaceName(siteType.getPlaceName());
            siteConsumptionDetails.setPrice(siteReservation.getPriceTotal());
            siteConsumptionDetails.setOperatorNum(siteReservation.getOperatorNum());
            siteConsumptionDetails.setPlaceType(siteType.getPlaceType());
            siteConsumptionDetails.setPaymentMethod(siteReservation.getPayMethod());
            siteConsumptionDetails.setVipType(siteReservation.getVipType());
            siteConsumptionDetails.setState("1");
            return siteConsumptionDetailsRepository.insertAll(siteConsumptionDetails);
        } else {
            return s;
        }

    }

    @Transactional
    public int updatePayData(SiteReservation siteReservation,int plyKey){
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        SiteType siteType = siteTypeRepository.selectByPlaceKey(plyKey);
        List<SiteReservation> siteReservations = siteReservationRepository.selectByMore(siteReservation.getState(),String.valueOf(siteReservation.getScheduledDate()),plyKey,siteReservation.getVipNum());
        int s = 0;
        for(int i = 0;i <siteReservations.size();i++){
            siteReservations.get(i).setPlaceKey(siteType);
            siteReservations.get(i).setState("1");
            siteReservations.get(i).setPrice(siteReservation.getPrice());
            siteReservations.get(i).setPayMethod(siteReservation.getPayMethod());
            siteReservations.get(i).setOperatorNum(siteReservation.getOperatorNum());
            siteReservations.get(i).setVipType(siteReservation.getVipType());
            s = siteReservationRepository.updateData(siteReservations.get(i));
        }
        if(s > 0 ){
            SiteConsumptionDetails siteConsumptionDetails = new SiteConsumptionDetails();
            siteConsumptionDetails.setSiteOrder(siteReservations.get(0).getSiteOrder());
            siteConsumptionDetails.setDate(date);
            siteConsumptionDetails.setVipNum(siteReservation.getVipNum());
            siteConsumptionDetails.setVipName(siteReservation.getVipName());
            siteConsumptionDetails.setVipTel(siteReservation.getPhone());
            siteConsumptionDetails.setPlaceName(siteType.getPlaceName());
            siteConsumptionDetails.setPrice(siteReservation.getTimePrice());
            siteConsumptionDetails.setOperatorNum(siteReservation.getOperatorNum());
            siteConsumptionDetails.setPlaceType(siteType.getPlaceType());
            siteConsumptionDetails.setPaymentMethod(siteReservation.getPayMethod());
            siteConsumptionDetails.setVipType(siteReservation.getVipType());
            siteConsumptionDetails.setState("1");
            return siteConsumptionDetailsRepository.insertAll(siteConsumptionDetails);

        } else {
            return 0;
        }
    }

    public int unsubscribe(String scheduledDate,int plyKey,String vipNum,String state){
        System.out.println("scheduledDate ="+scheduledDate);
        System.out.println("plyKey ="+plyKey);
        System.out.println("vipNum ="+vipNum);
        List<SiteReservation> siteReservations = siteReservationRepository.selectByState1(state,scheduledDate,plyKey,vipNum);
        int s = 0;
        for(int i = 0;i <siteReservations.size();i++){
            siteReservations.get(i).setState("-1");
           s = siteReservationRepository.updateData(siteReservations.get(i));
        }

        if(s > 0){
            SiteConsumptionDetails siteConsumptionDetails =  siteConsumptionDetailsRepository.selectBySiteOrder(siteReservations.get(0).getSiteOrder());
            if(siteConsumptionDetails == null){
                return 1;
            } else {
                siteConsumptionDetails.setState("-1");
                return siteConsumptionDetailsRepository.updateData(siteConsumptionDetails);
            }
        } else {
            return 0;
        }
    }

    @Transactional
    public int fixedSite(SiteReservation siteReservation, String[] revTime,int plyKey,String startFixedDate,String endFixedDate){
        List<String> dateStrList = collectLocalDates(LocalDate.parse(startFixedDate), LocalDate.parse(endFixedDate));

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date(System.currentTimeMillis());//获取当前时间

        SiteType siteType = siteTypeRepository.selectByPlaceKey(plyKey);


        int s = 0;

        for (int j = 0;j<dateStrList.size();j++){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date utilDate = null;
            try {
                utilDate = format.parse(dateStrList.get(j));
            } catch (Exception e) {
                e.printStackTrace();
            }
            Date sqlDate = new Date(utilDate.getTime());
            for(int i = 0;i <revTime.length;i++){
                System.out.println("sqlDate = "+sqlDate);
                SiteTime siteTime = siteTimeRepository.selectByTimeDate(revTime[i]);
                SiteReservation siteRev = siteReservationRepository.selectCheck(String.valueOf(sqlDate),plyKey,siteTime.getTimeKey());
                if(siteRev == null){//没有被预定
                    siteReservation.setScheduledDate(sqlDate);
                    siteReservation.setTimeKey(siteTime);
                    siteReservation.setPlaceKey(siteType);
                    siteReservation.setState("5");
                    siteReservation.setVipType("会员");
                    siteReservation.setSiteOrder(String.valueOf(date.getTime()));
                    s = siteReservationRepository.insertAll(siteReservation);
                } else {
                    s = 0;
                    System.out.println("s b = "+s);
                    break;
                }
            }
        }
        System.out.println("s 2 = "+s);
        if(s > 0){
            return 1;
        } else {
            return 0;
        }
    }

    public List<String> collectLocalDates(LocalDate start, LocalDate end){
        // 用起始时间作为流的源头，按照每次加一天的方式创建一个无限流
        return Stream.iterate(start, localDate -> localDate.plusDays(1))
                // 截断无限流，长度为起始时间和结束时间的差+1个
                .limit(ChronoUnit.DAYS.between(start, end) + 1)
                // 由于最后要的是字符串，所以map转换一下
                .map(LocalDate::toString)
                // 把流收集为List
                .collect(Collectors.toList());
    }

}
